﻿

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;

using Gift.DAL;
using Gift.Model;
using System.Data;
using System.Text;
using System.Xml;
using Gift.WebApp;
using AjaxPro;
using Gift.Utile;

namespace WebApp.admin.goods
{
    public partial class goodsAdd : BaseAdmin
    {
        // Fields
      
        tbGoodsCategory oGoodsCategory = new tbGoodsCategory();
      
        tbGoods oGoods = new tbGoods();
       

        // Methods
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                this.oGoods.category = base.Request.Form["addCategory"];
                this.oGoods.brand = Convert.ToInt32(base.Request.Form["brand"]);
                this.oGoods.goodsType = Convert.ToInt32(base.Request.Form["sGoodsType"]);
                this.oGoods.goodsName = this.txtGoodsName.Value;
                this.oGoods.goodsNo = this.txtGoodsNo.Value;
                this.oGoods.origin = this.txtOrigin.Value;
                this.oGoods.isBest = MathLibrary.ConvertNumToBool(base.Request.Form["isBest"]);
                this.oGoods.isNew = MathLibrary.ConvertNumToBool(base.Request.Form["isNew"]);
                this.oGoods.isTopSelling = MathLibrary.ConvertNumToBool(base.Request.Form["isTopSelling"]);
                this.oGoods.isShelves = MathLibrary.ConvertNumToBool(base.Request.Form["isShelves"]);
                this.oGoods.isPromote = MathLibrary.ConvertNumToBool(base.Request.Form["isPromote"]);
                this.oGoods.isUserDiscount = MathLibrary.ConvertNumToBool(base.Request.Form["isUserDiscount"]);
                this.oGoods.isOrderFromFreight = this.cbIsOrderFromFreight.Checked;
                this.oGoods.isDiscount = this.cbIsDiscount.Checked;
                this.oGoods.isTotalReduce = this.cbIsTotalReduce.Checked;
                this.oGoods.isGifts = this.cbIsGifts.Checked;
                this.oGoods.isSendIntegral = this.cbIsSendIntegral.Checked;
                this.oGoods.isFromFreight = MathLibrary.ConvertNumToBool(base.Request.Form["isFromFreight"]);
                this.oGoods.freightTemplate = (this.oGoods.isFromFreight == true) ? 0 : Convert.ToInt32(base.Request.Form["freightTemplate"]);
                this.oGoods.keywords = this.txtKeywords.Value;
                this.oGoods.description = this.txtaDescription.Value;

                this.oGoods.creator = int.Parse(Administrator.AdminUserId);
                this.oGoods.goodsRemark = this.txtGoodsRemark.InnerText.Replace("'", "''");
                this.oGoods.isProfShelves = MathLibrary.ConvertNumToBool(base.Request.Form["isProfShelves"]);
                this.oGoods.professionType = this.ddlProfessionType.SelectedItem.Value == "" ? 0 : int.Parse(this.ddlProfessionType.SelectedItem.Value);
                this.oGoods.CompanyId = int.Parse(base.Administrator.CompanyId);
                this.oGoods.id = BaseFactory.theGoods.Add(this.oGoods);
                if (this.oGoods.id != 0)
                {
                    int num;
                    Array array = this.oGoods.category.Split(new char[] { ',' });
                    foreach (string str in array)
                    {
                        this.oGoodsCategory.goods = this.oGoods.id;
                        this.oGoodsCategory.category = Convert.ToInt32(str);
                        BaseFactory.theGoodsCategory.Add(this.oGoodsCategory);
                    }
                    ArrayList list = ArrayList.Adapter(base.Request.Form["barCode"].Split(new char[] { ',' }));
                    ArrayList list2 = ArrayList.Adapter(base.Request.Form["goodsArtno"].Split(new char[] { ',' }));
                    ArrayList list3 = ArrayList.Adapter(base.Request.Form["salePrice"].Split(new char[] { ',' }));
                    ArrayList list4 = ArrayList.Adapter(base.Request.Form["costPrice"].Split(new char[] { ',' }));
                    ArrayList list5 = ArrayList.Adapter(base.Request.Form["marketPrice"].Split(new char[] { ',' }));
                    ArrayList list6 = ArrayList.Adapter(base.Request.Form["giveIntegral"].Split(new char[] { ',' }));
                    ArrayList list7 = ArrayList.Adapter(base.Request.Form["goodsWeight"].Split(new char[] { ',' }));
                    ArrayList list8 = ArrayList.Adapter(base.Request.Form["selectWeightUnit"].Split(new char[] { ',' }));
                    ArrayList list9 = ArrayList.Adapter(base.Request.Form["inventory"].Split(new char[] { ',' }));
                    for (num = 0; num < list2.Count; num++)
                    {
                        tbGoodsEntitys goodsEntitys = new tbGoodsEntitys();
                        goodsEntitys.goods = this.oGoods.id;
                        goodsEntitys.barCode = list[num].ToString();
                        goodsEntitys.goodsArtno = list2[num].ToString();
                        goodsEntitys.salePrice = Convert.ToDecimal(list3[num]);
                        goodsEntitys.costPrice = Convert.ToDecimal(list4[num]);
                        goodsEntitys.marketPrice = Convert.ToDecimal(list5[num]);
                        goodsEntitys.integral = 0;
                        goodsEntitys.giveIntegral = Convert.ToDecimal(list6[num]);
                        goodsEntitys.goodsWeight = Convert.ToDecimal(list7[num]);
                        goodsEntitys.weightUnit = list8[num].ToString();
                        goodsEntitys.inventory = Convert.ToInt32(list9[num]);
                        goodsEntitys.id = BaseFactory.theGoodsEntitys.Add(goodsEntitys);
                        if (goodsEntitys.id != 0)
                        {
                            tbGoodsEntitysSpecifications ges = new tbGoodsEntitysSpecifications();
                            DataTable specifications = BaseFactory.theSpecifications.GetSpecificationsByCompanyId(int.Parse(base.Administrator.CompanyId));
                            foreach (DataRow row in specifications.Rows)
                            {
                                if (base.Request.Form["SpecificationsValue" + row["id"].ToString() + ""] != null)
                                {
                                    ges.goodsEntitys = goodsEntitys.id;
                                    ges.specifications = Convert.ToInt32(row["id"]);
                                    ges.specificationsValue = Convert.ToInt32(ArrayList.Adapter(base.Request.Form["SpecificationsValue" + row["id"].ToString() + ""].Split(new char[] { (char)0x2c }))[num]);
                                    BaseFactory.theGoodsEntitysSpecifications.Add(ges);
                                }
                            }
                        }
                    }
                    HttpFileCollection files = HttpContext.Current.Request.Files;
                    ArrayList list10 = ArrayList.Adapter(base.Request.Form["imgAlt"].Split(new char[] { ',' }));
                    for (num = 0; num < files.Count; num++)
                    {
                        tbGoodGallery goodGallery = new tbGoodGallery();
                        goodGallery.goods = this.oGoods.id;
                        string str2 = DateTime.Now.ToString("yyyyMMddHHssffffff");
                        goodGallery.bigImg = "/cn/goods/big/" + str2 + Path.GetExtension(files[num].FileName);
                        goodGallery.smallImg = "/cn/goods/small/" + str2 + Path.GetExtension(files[num].FileName);
                        goodGallery.thumbImg = "/cn/goods/thumb/" + str2 + Path.GetExtension(files[num].FileName);
                        files[num].SaveAs(base.Server.MapPath(goodGallery.bigImg));
                        ThumbnailImage image = new ThumbnailImage();
                        image.GetThumbnail(base.Server.MapPath(goodGallery.bigImg), base.Server.MapPath(goodGallery.smallImg), 500, 500, 1, Color.White);
                        image.GetThumbnail(base.Server.MapPath(goodGallery.bigImg), base.Server.MapPath(goodGallery.thumbImg), 200, 200, 1, Color.White);
                        goodGallery.imgAlt = list10[num].ToString();
                        BaseFactory.theGoodGallery.Add(goodGallery);
                    }
                    DataTable atrributesByGoodsTypeAndState = BaseFactory.theAttributes.GetAtrributesByGoodsTypeAndState(this.oGoods.goodsType, 1);
                    int num2 = 0;
                    if (atrributesByGoodsTypeAndState.Rows.Count > 0)
                    {
                        ArrayList list11 = new ArrayList();
                        if (base.Request.Form["atrributesValue"] != null)
                        {
                            list11 = ArrayList.Adapter(base.Request.Form["atrributesValue"].Split(new char[] { ',' }));
                        }
                        for (int i = 0; i < atrributesByGoodsTypeAndState.Rows.Count; i++)
                        {
                            tbGoodsAttribute goodsAttribute = new tbGoodsAttribute();
                            goodsAttribute.goods = this.oGoods.id;
                            goodsAttribute.attributes = Convert.ToInt32(atrributesByGoodsTypeAndState.Rows[i]["id"]);
                            switch (Convert.ToInt32(atrributesByGoodsTypeAndState.Rows[i]["attributeInputType"]))
                            {
                                case 0:
                                case 1:
                                case 2:
                                case 5:
                                    goodsAttribute.inputValue = list11[num2].ToString();
                                    goodsAttribute.attributeValue = "0";
                                    BaseFactory.theGoodsAttribute.Add(goodsAttribute);
                                    num2++;
                                    break;

                                case 3:
                                    {
                                        string str3 = "rdAtrributes" + atrributesByGoodsTypeAndState.Rows[i]["id"].ToString();
                                        goodsAttribute.attributeValue = base.Request.Form[str3];
                                        goodsAttribute.inputValue = "";
                                        BaseFactory.theGoodsAttribute.Add(goodsAttribute);
                                        break;
                                    }
                                case 4:
                                    {
                                        string str4 = "cbAtrributes" + atrributesByGoodsTypeAndState.Rows[i]["id"].ToString();
                                        goodsAttribute.attributeValue = base.Request.Form[str4];
                                        goodsAttribute.inputValue = "";
                                        BaseFactory.theGoodsAttribute.Add(goodsAttribute);
                                        break;
                                    }
                            }
                        }
                    }
                    base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"添加成功！\"); window.location.href='goodsList.aspx';</script>");
                }
                base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"添加失败！\");</script>");
            }
            catch
            {
                base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"添加失败！\");</script>");
            }
        }

        protected StringBuilder CategoryBind()
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                this.RecursionCategory(sb, "00000000-0000-0000-0000-000000000000", int.Parse(base.Administrator.CompanyId));
            }
            catch
            {
            }
            return sb;
        }

        private void BindProfessionAreaType()
        {
            DataSet dsType = new DataSet();
            DALProfessionAreaType theType = new DALProfessionAreaType();
            dsType = theType.GetList("");
            if (dsType.Tables.Count > 0)
            {
                this.ddlProfessionType.DataSource = dsType.Tables[0].DefaultView;
                this.ddlProfessionType.DataTextField = "Name";
                this.ddlProfessionType.DataValueField = "Id";
                this.ddlProfessionType.DataBind();
            }
            this.ddlProfessionType.Items.Insert(0, new ListItem("选择所属专区..", ""));


        }

        protected StringBuilder FreightTemplateBind()
        {
            StringBuilder builder = new StringBuilder();
            try
            {
                DataTable freightTemplateByCompanyId = BaseFactory.theFreightTemplate.GetFreightTemplateByCompanyId(int.Parse(base.Administrator.CompanyId));
                foreach (DataRow row in freightTemplateByCompanyId.Rows)
                {
                    builder.AppendLine(string.Concat(new object[] { "<option value=\"", row["id"], "\">", row["freightTemplateName"], "</option>" }));
                }
            }
            catch
            {
            }
            return builder;
        }

        protected StringBuilder GoodsTypeBind()
        {
            StringBuilder builder = new StringBuilder();
            try
            {
                DataTable goodsType = BaseFactory.theGoodsType.GetGoodsTypeByCompanyId(int.Parse(base.Administrator.CompanyId));
                foreach (DataRow row in goodsType.Rows)
                {
                    builder.AppendLine("<option value=\"" + row["id"].ToString() + "\">" + row["typeName"].ToString() + "</option>");
                }
            }
            catch
            {
            }
            return builder;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //if ((HttpContext.Current.Session["admin_user"] == null) && (HttpContext.Current.Session["language_version"] == null))
            //{
            //    base.ClientScript.RegisterStartupScript(base.GetType(), "sJs", "top.location=\"login.html\";", true);
            //}
          
            if (!base.IsPostBack)
            {
                base.ValidateLoginRule(Gift.Model.ENUM.ERule.GoodsAdd);
                Utility.RegisterTypeForAjax(typeof(Goods_ajax));
                this.BindProfessionAreaType();
                this.rdIsBest0.Checked = true;
                this.rdIsNew0.Checked = true;
                this.rdIsTopSelling0.Checked = true;
                this.rdIsShelves1.Checked = true;
                this.rdIsProfShelves1.Checked = true;
                this.rdIsPromote1.Checked = true;
                this.rdIsPromote0.Checked = true;
                this.rdIsUserDiscount1.Checked = true;
                this.cbIsOrderFromFreight.Checked = true;
                this.cbIsDiscount.Checked = true;
                this.cbIsTotalReduce.Checked = true;
                this.cbIsGifts.Checked = true;
                this.cbIsSendIntegral.Checked = true;
                this.rdIsFromFreight0.Checked = true;
                this.txtGoodsName.Focus();
            }
        }

        private void RecursionCategory(StringBuilder sb, string parentCategory, int companyId)
        {
            DataTable table = BaseFactory.theCategory.GetCategoryByParentIdAndCompanyIdAndIsShow(parentCategory, companyId, -1);
            if (table.Rows.Count > 0)
            {
                foreach (DataRow row in table.Rows)
                {
                    string str = "";
                    int num = Convert.ToInt32(row["depth"]);
                    if (num > 0)
                    {
                        for (int i = 0; i < num; i++)
                        {
                            str = str + "&nbsp;&nbsp;&nbsp;&nbsp;";
                        }
                        str = str + "┣";
                    }
                    sb.AppendLine("<option value=\"" + row["categoryIdentity"].ToString() + "\">" + str + row["categoryName"].ToString() + "</option>");
                    this.RecursionCategory(sb, row["id"].ToString(), companyId);
                }
            }
        }

        protected StringBuilder SpecificationsBind()
        {
            StringBuilder builder = new StringBuilder();
            try
            {
                DataTable specifications = BaseFactory.theSpecifications.GetSpecificationsByCompanyId(int.Parse(base.Administrator.CompanyId));
                bool flag = false;
                foreach (DataRow row in specifications.Rows)
                {
                    builder.AppendLine("" + (!flag ? "" : "<br/>") + "<input id=\"cb" + row["id"].ToString() + "\" value=\"" + row["id"].ToString() + "\" name=\"ss\" type=\"checkbox\" onclick=\"getSpecifications(" + row["id"].ToString() + ",this);\" />[" + row["specificationsName"].ToString() + "]");
                    flag = true;
                }
            }
            catch
            {
            }
            return builder;
        }

    }
}